package challenge;

import java.util.*;

/**
 * Created by Tzachi on 18/10/2014.
 */
public class Anagrams {


    public static boolean isAnagram(String s, String t) {
        if (s == null || t == null) {
            return false;
        }
        if (s.isEmpty() && t.isEmpty()){
            return true;
        }
        char[] sChars = s.toCharArray();
        char[] tChars = t.toCharArray();
        Arrays.sort(sChars);
        Arrays.sort(tChars);
        String sSorted = new String(sChars);
        String tSorted = new String(tChars);
        return sSorted.equals(tSorted);
    }

    public static List<List<String>> anagramLists(List<String> input) {
        List<List<String>> result = new LinkedList<>();
        if (input == null) {
            return result;
        }
        Map<String, List<String>> map = new HashMap<>();
        for (String currStr : input) {
            char[] sortedCharArray = currStr.toCharArray();
            Arrays.sort(sortedCharArray);
            String sortedStr = new String(sortedCharArray);
            List<String> list = map.get(sortedStr);
            if (list == null) {
                list = new LinkedList<>();
                map.put(sortedStr, list);
            }
            list.add(currStr);
        }
        for (List<String> strings : map.values()) {
            result.add(strings);
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(isAnagram("abc", "cba"));
        System.out.println(isAnagram("aac", "caa"));
        System.out.println(isAnagram("adc", "caa"));

        List<String> ss = new LinkedList<>();
        ss.add("abc");
        ss.add("acb");
        ss.add("dd");
        List<List<String>> i = anagramLists(ss);
        System.out.println();
    }


}
